#include <iostream>
#include <vector>
#include <unistd.h>
#include "Mythread.hpp"
#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>

using blockqueue_t = BlockQueue<Task>;

void hello()
{
	std::cout << "hello" << std::endl;
}

void Consumer(blockqueue_t &bq)
{
	while (true)
	{
		// int data;
		Task t;			//获取到要执行的
		bq.Pop(&t);
		// t.Excute();
		t();
		// std::cout << "Consumer Consum data is : " << t.ResultToString() << std::endl;
		sleep(2);
	}
}

void Producter(blockqueue_t &bq)
{
	srand(time(nullptr));
	// int cnt = 1;
	while (true)
	{
		// int a = rand() % 100 - 1;
		// usleep(1234);
		// int b = rand() % 10 - 1;
		Task t = hello;
		bq.Enqueue(t);
		// std::cout << "Productor product data is : " << t.DebugToString() << std::endl;
		// cnt++;
	}
}

void StartComm(std::vector<Mythread::Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq, Mythread::func_t<blockqueue_t> func)
{
	for (int i = 0; i < num; i++)
	{
		std::string name = "thread=" + std::to_string(i);
		threads->emplace_back(func, bq, name);
		threads->back().start();
	}
}

void StartProduct(std::vector<Mythread::Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq)
{
	StartComm(threads, num, bq, Producter);
}

void StartConsumer(std::vector<Mythread::Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq)
{
	StartComm(threads, num, bq, Consumer);
}

void WaitThreads(std::vector<Mythread::Thread<blockqueue_t>> &threads)
{
	for (auto &tid : threads)
	{
		tid.join();
	}
}

int main()
{
	blockqueue_t *bq = new blockqueue_t(1);
	std::vector<Mythread::Thread<blockqueue_t>> threads;
	StartProduct(&threads, 1, *bq);
	StartConsumer(&threads, 1, *bq);
	WaitThreads(threads);
	return 0;
}